<?php

namespace App\Models\SystemManagement;

use App\Models\CommonModel;
use App\Models\Error;
use App\Models\Constant\Fields;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

class Employee extends CommonModel
{
    protected $table = 'employees';
    public $primaryKey = 'id';
    protected $guarded = ['photo_id'];
    protected $hidden = ['deleted_at','created_at','updated_at'];

    /**
     * @param $data
     * @return Error
     * 添加员工
     */
    static function addData($data){
        DB::beginTransaction();
        try {
            $data['mark'] = generateMark('YG');
            $data['creator'] = session('login.name')?session('login.name'):'admin';
            if(isset($data['photo_id'])){
                $file_id = $data['photo_id'];
                unset($data['photo_id']);
            }
            $employee = self::create($data);
            if(!empty($file_id)){
                $file_data['employee_id'] = $employee->id;
                $file_data['file_id'] = $file_id;
                try{
                    EmployeeFile::create($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                    // dd($e);
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
            }
            DB::commit();
            return response()->json(encodeMsg($employee,201));
        } catch (QueryException $e) {
            DB::rollBack();
            // dd($e);
            return response()->json(encodeMsg(['message' => '数据添加失败!'],400));
        }
    }

    /**
     * @param $data
     * @param $id
     * @return mixed
     * 修改员工
     */
    static function updateData($data,$id){
        $employee = Employee::find($id);
        if($employee == []) {
            return response()->json(encodeMsg(["message" => "没有该员工信息!"], 404));
        }
        DB::beginTransaction();
        try {
            $data['disable'] = session('login.name')?session('login.name'):'admin';
            if(isset($data['photo_id']) && !empty($data['photo_id'])){
                $employeeFile = EmployeeFile::where('employee_id',$id)->first('id');
                $file_data['employee_id'] = $id;
                $file_data['file_id'] = $data['photo_id'];
                try{
                    EmployeeFile::where('id',$employeeFile['id'])->delete();
                    EmployeeFile::create($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                     dd($e);
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
                unset($data['photo_id']);
            }
            $employee->update($data);
            DB::commit();
            return response()->json(encodeMsg($employee,201));
        } catch (QueryException $e) {
            DB::rollBack();
            dd($e);
            return response()->json(encodeMsg(['message' => '数据添加失败!'],400));
        }
    }

    //查看列表
    static function getListByCond($request)
    {
        $per_page = $request->input('per_page',10);
        return self::orderBy('id','desc')
                ->with(['organization','department','post','skill','files'])
                ->where(function($query) use ($request){
                    //检测当前的请求中是否包含device_name、principal参数
                    $name = $request->input('name', '');//员工姓名
                    $id_no = $request->input('id_no','');//证件号码
                    $mark = $request->input('mark','');//工号
                    $department_id = $request->input('department_id','');
                    $entry_start_time = $request->input('entry_start_time');
                    $entry_end_time = $request->input('entry_end_time');
                    if(!empty($name)) {
                        $query->where('name','like','%'.$name.'%');
                    }
                    if(!empty($id_no)) {
                        $query->where('id_no','=',$id_no);
                    }
                    if(!empty($mark)) {
                        $query->where('mark','=',$mark);
                    }
                    if(!empty($department_id)) {
                        $query->where('department_id','=',$department_id);
                    }
                    if(!empty($entry_start_time) && !empty($entry_end_time)) {
                        $query->whereBetween('entry_time',[$entry_start_time, $entry_end_time]);
                    }
                })
                ->paginate($per_page);
    }

    /**
     * @param $skip
     * @param $take
     * @return mixed
     * 员工列表
     */
    static function getPageData($per){
        $query = self::with(['organization','department','post','skill','files'])->orderBy('id','desc')->paginate($per);
        return $query;
    }

    /**
     * @param $id
     * @return mixed
     * 查看员工详情
     */
    static function getOne($id){
        $query = self::with(['organization','department','post','skill','files'])->find($id);
        return $query;
    }

    /**
     * @param $ids
     * @return Error
     * 删除员工
     */
    static function del($ids){
        $res = self::batchDelTableData($ids,new self());
        return $res;
    }

    //所属组织
    public function organization()
    {
        return $this->belongsTo(self::$SYSTEM.'\Organization',Fields::ORGAN_ID,Fields::ID)->select('id','name');
    }

    //所属部门
    public function department()
    {
        return $this->belongsTo(self::$SYSTEM.'\Department',Fields::DEPART_ID,Fields::ID)->select('id','name');
    }

    //所属岗位
    public function post()
    {
        return $this->belongsTo(self::$SYSTEM.'\Post',Fields::POST_ID,Fields::ID)->select('id','name');
    }

    //所属岗位职级
    public function skill()
    {
        return $this->belongsTo(self::$SYSTEM.'\Skill',Fields::SKILL_ID,Fields::ID)->select('id','name');
    }

    //人员信息中间表
    public function personInfo()
    {
        return $this->hasOne('\App\Models\PersonInfoManagement\PersonInfo',Fields::EMPLOYEE_ID)->with('banci');
    }

    function files()
    {
        return $this->hasMany(EmployeeFile::class,'employee_id')->with('file');
    }

}
